package com.suxin.plugin.intergration.application;

import com.suxin.plugin.intergration.IntegrationConfiguration;
import com.suxin.plugin.intergration.manager.DefaultManagerFactory;
import com.suxin.plugin.intergration.manager.plugin.PluginManager;
import com.suxin.plugin.intergration.manager.user.DefaultPluginUser;
import com.suxin.plugin.intergration.manager.user.PluginUser;
import com.suxin.plugin.operator.DefaultPluginOperator;
import com.suxin.plugin.operator.PluginOperator;
import org.springframework.context.ApplicationContext;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Tang
 * @classname DefaultPluginApplication
 * @description [  ]
 * @date 2022/6/26 18:37
 */
public class DefaultPluginApplication extends AbstractPluginApplication {

    private final AtomicBoolean beInitialized = new AtomicBoolean(false);

    private DefaultManagerFactory pluginManagerFactory;

    private PluginUser pluginUser;

    private PluginManager pluginManager;

    private DefaultPluginOperator pluginOperator;

    public DefaultPluginApplication() {
    }

    @Override
    public PluginOperator getPluginOperator() {
        return pluginOperator;
    }

    @Override
    public PluginUser getPluginUser() {
        return pluginUser;
    }

    @Override
    public void initialize(ApplicationContext applicationContext) {
        Objects.requireNonNull(applicationContext, "ApplicationContext cant be null");
        if (beInitialized.get()) {
            throw new RuntimeException("Plugin has been initialized");
        }
        // 加载插件配置类
        IntegrationConfiguration integrationConfiguration = applicationContext.getBean(IntegrationConfiguration.class);
        if (pluginManagerFactory == null) {
            pluginManagerFactory = new DefaultManagerFactory(integrationConfiguration);
        }
        pluginManager = pluginManagerFactory.getPluginManager();
        pluginUser = new DefaultPluginUser(pluginManager, applicationContext);
        // 定义插件操作者
        pluginOperator = new DefaultPluginOperator(integrationConfiguration,
                applicationContext, pluginManager, pluginUser,this.listenerFactory);
        pluginOperator.initPlugins();
        beInitialized.set(true);
    }
}